import React, {Component} from 'react';
import CommentInput from './CommentInput';
import CommentList from './CommentList';
import PropTypes from 'prop-types';
import Card from './Card';
import './comment.css';
import './styles/card.css'

export default class ComponentApp extends Component {
    static propTypes = {
        comments: PropTypes.object
    }

    constructor() {
        super();
        this.state = {
            comments: []
        }
    }

    componentWillMount() {
        this._loadComments();
    }

    componentDidMount() {
        console.log('component did mount')
    }

    _loadComments() {
        let comments = localStorage.getItem("comments");
        if (comments) {
            this.setState({
                comments: JSON.parse(comments)
            })
        }
    }

    _saveComments(comments) {
        localStorage.setItem("comments", JSON.stringify(comments));
    }

   

    getContent(content) {
        if (!content) 
            return;
        if (!content.username) 
            return alert("请填写用户名!!!");
        if (!content.content) 
            return alert("请填写评论内容!!!");
        this
            .state
            .comments
            .push(content);
        this.setState({comments: this.state.comments})
        this._saveComments(this.state.comments);
    }

    handleCommentDelete(index){
        var curComments = this.state.comments;
        // var curComments = JSON.parse(localStorage.getItem("comments"));
    
        if(curComments){
            curComments.splice(index,1);
            this.setState({
                comments: curComments
            })
        }
        this._saveComments(curComments)
    }
    render() {
        return (
            <div className="wrapper">
                <CommentInput
                    onSubmit={this
                    .getContent
                    .bind(this)}/>
                <CommentList myComments={this.state.comments} onDeleteComment={this.handleCommentDelete.bind(this)}/>

                <Card>
                    <div className="inside-box">
                        <h3>这是一个内部盒子</h3>
                        <p
                            style={{
                            color: "blue"
                        }}>这是react的学习</p>
                        <span>这是props.children的学习<code>console.log("react")</code>
                        </span>
                    </div>
                </Card>
            </div>
        )

    }
}